package com.sparrow.resource.reader.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.sparrow.resource.reader.ResourceReader;

import java.io.File;
import java.lang.reflect.Type;
import java.util.List;

public class JSONResourceReader implements ResourceReader {

    private ObjectMapper objectMapper = new ObjectMapper();

    private TypeFactory typeFactory = objectMapper.getTypeFactory();

    @Override
    public <T> List<T> read(File file, Class<? extends T> clazz) {
        try {
            return objectMapper.readValue(file, new TypeReference<List<T>>() {
                @Override
                public Type getType() {
                    return typeFactory.constructParametricType(List.class, clazz);
                }
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
